<template>
  <el-dialog
      v-model="dialogVisible"
      title="商品详情"
      width="700px"
      :before-close="handleCloseDialog"
  >
    <el-form
        ref="detailFormRef"
        :model="detailForm"
        label-width="120px"
        class="product-detail-form"
        disabled
    >
      <el-row :gutter="16">
        <el-col :span="12">
          <el-form-item label="商品编号">
            <el-input
                v-model="detailForm.code"
                class="product-detail-form-input"
                readonly
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="商品名称">
            <el-input
                v-model="detailForm.name"
                class="product-detail-form-input"
                readonly
            />
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="16">
        <el-col :span="12">
          <el-form-item label="品牌">
            <el-input
                v-model="detailForm.brand"
                class="product-detail-form-input"
                readonly
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="型号/规格">
            <el-input
                v-model="detailForm.model"
                class="product-detail-form-input"
                readonly
            />
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="16">
        <el-col :span="12">
          <el-form-item label="单位">
            <el-input
                v-model="detailForm.unit"
                class="product-detail-form-input"
                readonly
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="分类">
            <el-input
                v-model="detailForm.categoryName"
                class="product-detail-form-input"
                readonly
            />
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="16">
        <el-col :span="12">
          <el-form-item label="参考采购价">
            <el-input
                v-model="detailForm.purchasePrice"
                class="product-detail-form-input"
                readonly
            >
              <template #prefix>¥</template>
            </el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="默认销售价">
            <el-input
                v-model="detailForm.salePrice"
                class="product-detail-form-input"
                readonly
            >
              <template #prefix>¥</template>
            </el-input>
          </el-form-item>
        </el-col>
      </el-row>

      <el-form-item label="商品图片">
        <div v-if="detailForm.image" class="product-detail-form-image-preview">
          <img :src="getImageDisplayUrl(detailForm.image)" alt="商品图片"
               class="product-detail-form-image-preview-img"/>
        </div>
        <div v-else class="product-detail-form-image-placeholder">
          <el-icon class="product-detail-form-image-placeholder-icon">
            <Picture/>
          </el-icon>
          <div class="product-detail-form-image-placeholder-text">暂无图片</div>
        </div>
      </el-form-item>
    </el-form>

    <template #footer>
      <div class="product-detail-dialog-footer">
        <el-button @click="handleCloseDialog">关闭</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup>
import {ref, reactive, watch} from 'vue'
import {ElMessage} from 'element-plus'
import {getProduct} from "../../../api/productApi.js";
import {getCategoriesTree} from "../../../api/categoryApi.js";

// 定义props
const props = defineProps({
  visible: {
    type: Boolean,
    default: false
  },
  productId: {
    type: Number,
    default: null
  }
})

// 定义emits
const emits = defineEmits(['update:visible'])

// 对话框显示状态
const dialogVisible = ref(false)

// 表单引用
const detailFormRef = ref()

// 分类树数据
const categoryTreeData = ref([])

// 详情表单数据
const detailForm = reactive({
  code: '',
  name: '',
  brand: '',
  model: '',
  unit: '',
  purchasePrice: '',
  salePrice: '',
  image: '',
  categoryName: ''
})

// 监听visible变化
watch(() => props.visible, async (newVal) => {
  dialogVisible.value = newVal
  if (newVal && props.productId) {
    // 并行获取分类和商品数据，并等待它们全部完成
    const [, productData] = await Promise.all([loadCategoryTree(), loadProductData()])
    if (productData) {
      initFormData(productData)
    }
  }
})

// 监听dialogVisible变化，同步到父组件
watch(dialogVisible, (newVal) => {
  if (!newVal) {
    emits('update:visible', false)
  }
})

// 加载商品详情数据
const loadProductData = async () => {
  if (!props.productId) return

  try {
    // 获取商品详情
    return await getProduct(props.productId)
  } catch (error) {
    console.error('获取商品详情失败:', error)
    ElMessage.error('获取商品详情失败')
    return null
  }
}

// 加载分类树数据
const loadCategoryTree = async () => {
  try {
    const res = await getCategoriesTree()
    if (res && typeof res === 'object' && !Array.isArray(res)) {
      categoryTreeData.value = [res]
    } else if (Array.isArray(res)) {
      categoryTreeData.value = res
    } else {
      categoryTreeData.value = []
    }
  } catch (error) {
    console.error('加载分类树失败:', error)
    ElMessage.error('加载分类数据失败')
  }
}

// 递归查找分类名称
const findCategoryName = (tree, id) => {
  for (const node of tree) {
    if (node.id === id) {
      return node.name
    }
    if (node.children) {
      const found = findCategoryName(node.children, id)
      if (found) return found
    }
  }
  return null
}

// 初始化表单数据
const initFormData = (productData) => {
  if (productData) {
    detailForm.code = productData.code || ''
    detailForm.name = productData.name || ''
    detailForm.brand = productData.brand || ''
    detailForm.model = productData.model || ''
    detailForm.unit = productData.unit || ''
    detailForm.purchasePrice = productData.purchasePrice ? `${productData.purchasePrice}` : ''
    detailForm.salePrice = productData.salePrice ? `${productData.salePrice}` : ''
    detailForm.image = productData.image || ''
    detailForm.categoryName = findCategoryName(categoryTreeData.value, productData.categoryId) || '未分类'
  }
}

// 关闭对话框
const handleCloseDialog = () => {
  dialogVisible.value = false
  resetForm()
}

// 重置表单
const resetForm = () => {
  detailForm.code = ''
  detailForm.name = ''
  detailForm.brand = ''
  detailForm.model = ''
  detailForm.unit = ''
  detailForm.purchasePrice = ''
  detailForm.salePrice = ''
  detailForm.image = ''
  detailForm.categoryName = ''
}

// 获取图片显示URL
const getImageDisplayUrl = (imagePath) => {
  // 通过后端接口访问本地文件
  if (imagePath) {
    return `/api/file/image?path=${encodeURIComponent(imagePath)}`
  }
  return imagePath
}
</script>

<style scoped lang="scss">
.product-detail {
  &-form {
    padding: 16px 0;

    &-input {
      width: 100%;

      :deep(.el-input__inner) {
        background-color: #f5f7fa;
        border-color: #e4e7ed;
        color: #606266;
        cursor: not-allowed;
      }
    }

    &-image {
      &-preview {
        width: 120px;
        height: 120px;
        border: 1px solid #d9d9d9;
        border-radius: 6px;
        overflow: hidden;

        &-img {
          width: 100%;
          height: 100%;
          object-fit: cover;
        }
      }

      &-placeholder {
        display: flex;
        flex-direction: column;
        align-items: center;
        justify-content: center;
        width: 120px;
        height: 120px;
        border: 1px dashed #d9d9d9;
        border-radius: 6px;
        background-color: #f5f7fa;

        &-icon {
          font-size: 28px;
          color: #c0c4cc;
          margin-bottom: 8px;
        }

        &-text {
          font-size: 14px;
          color: #909399;
          text-align: center;
        }
      }
    }
  }

  &-dialog {
    &-footer {
      display: flex;
      justify-content: center;
      gap: 8px;
    }
  }
}
</style>
